# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
# ========= 导入数据类 ==============
from trainweb.models import Trainee
from basicweb.models import Line, Department


def list_values_by_employee(request):
    """获取某一个员工的培训列表"""
    # 获取传递的值
    page = int(request.POST.get('page'))
    limit = int(request.POST.get('limit'))
    eid = request.POST.get('eid')
    # 获取内容
    objs = list(
        Trainee.objects.filter(eid=eid).values('id', 'eid', 'create_time', 'position_id', 'position__name',
                                               'position__department_id',
                                               'position__department__name', 'position__department__line_id',
                                               'position__department__line__name'))
    # 分页
    one_page_data = objs[(page - 1) * limit: page * limit]
    # 返回---表格所需的样式
    return JsonResponse({'code': 0, 'count': len(objs), 'data': one_page_data})


def add_value(request):
    """为员工添加培训课程"""
    # 获取传递的值
    position_list = request.POST.get('position').split(",")
    eid = request.POST.get("eid")
    name = request.POST.get("name")
    # 定义返回的数据集合
    res = {'status': True}
    # 判断是否为某一个员工安排过当前的课程
    for item in position_list:
        # 判断是否有内容
        is_exists = Trainee.objects.filter(eid=eid, position_id=int(item)).exists()
        # 判断是否存在
        if is_exists:
            res['status'] = False
            res['error'] = "当前已为该员工共安排过课程【职位编号：" + item + "】"
            # 返回
            return JsonResponse(res)
    # 使用异常处理添加
    try:
        # 开始添加
        for item in position_list:
            Trainee.objects.create(eid=eid, name=name, position_id=int(item), status_id=4,
                                   create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    except Exception as e:
        res['status'] = False
        res['error'] = "添加培训内容到数据库出现异常，具体原因：" + str(e)

    # 返回
    return JsonResponse(res)


def del_value(request):
    """删除安排的职位培训"""
    # 接受传递的值
    eid = request.POST.get('eid')
    position_id = request.POST.get('position_id')
    # 判断当前培训是否开始，如果开始不允许删除！！！【预留】
    # 定义返回的数据集合
    res = {'status': True}
    # 使用异常处理添加
    try:
        Trainee.objects.filter(eid=eid, position_id=position_id).delete()
    except Exception as e:
        res['status'] = False
        res['error'] = "删除培训内容同步到数据库出现异常，具体原因：" + str(e)

    # 返回
    return JsonResponse(res)


def get_train_employee(request):
    """获取当前产线下参加培训的所有员工信息"""
    # 获取当前的产线
    line = request.session.get('current_line')
    # 获取当前产线下所有的参加培训的员工
    obj_trainees = list(Trainee.objects.filter(position__department__line_id=line).distinct().values('eid', 'name'))
    # 定义数据结构
    data = []
    # 遍历
    for item in obj_trainees:
        # 附加到集合
        data.append({'name': item.get('eid') + "--" + item.get('name'), 'value': item.get('eid')})

    # 获取产线的名称
    obj_line = Line.objects.filter(id=line).first()
    # 返回
    return JsonResponse({'data': data, 'line_id':  obj_line.id, 'line_name': obj_line.name})


def get_department_by_trainee_employee(request):
    """获取某一个员工所参加培训的部门"""
    # 获取当前的产线
    line = request.session.get('current_line')
    # 获取前台传递的员工信息
    employee_id = request.POST.get('employee_id')
    # 获取符合条件的部门信息
    obj_trainee = list(Trainee.objects.filter(position__department__line_id=line,
                                         eid=employee_id).distinct().values('position__department_id', 'position__department__name'))
    # 定义集合
    data = []
    # 遍历
    for item in obj_trainee:
        data.append({'name': item.get('position__department__name') , 'value': item.get('position__department_id') })

    # 返回
    return JsonResponse({'data': data})


def get_position_by_trainee_department(request):
    """获取相应员工参加相应部门下的职位列表"""
    # 获取当前的产线
    line = request.session.get('current_line')
    # 获取前台传递的员工信息
    department_id = request.POST.get('department_id')
    # 获取符合条件的部门信息
    obj_trainee = list(Trainee.objects.filter(position__department__line_id=line,
                                             position__department_id=department_id).distinct().values('position_id',
                                                                                 'position__name'))
    # 定义集合
    data = []
    # 遍历
    for item in obj_trainee:
        data.append({'name': item.get('position__name'), 'value': item.get('position_id')})

    # 返回
    return JsonResponse({'data': data})
